/* eslint-disable no-await-in-loop */
/* eslint-disable no-undef */
import {
  getTaxConfig,
  sendMessageToContent,
  getCurrentVersion,
  onMessageAndNotifications,
  onMessageAndSendToSaas,
  updateTab,
  autoClosePage,
  tableDetail,
  getIdentify,
  compareCwbbZd
} from './utils.js';
import { caishui } from '../lib/caishui.js';

const initInvoiceInfo = (invoiceInfoData, workTab) => {
  Object.assign(window.invoiceInfo, invoiceInfoData);
};

let closeTabs = [];

const initBaseInfo = (companyInfo, saasTab) => {
  let taxConfig = getTaxConfig(companyInfo);

  if (!taxConfig.length) {
    caishui.notifications('暂不支持该省市的一键报税！');
    return;
  }
  if (/上海|江西/.test(taxConfig[0].name)) {
    if (!companyInfo.nationalTaxId) {
      caishui.notifications('请到crm中补充国税纳税人识别号！');
      return;
    }
  }

  Object.assign(baseInfo, { companyInfo, taxConfig, saasTab });
  window.taxGovInfo = {};

  let nationTaxSite = taxConfig.find(item => {
    return item.type === 'nation';
  });
  if (nationTaxSite && nationTaxSite.url) {
    chrome.tabs.create({
      url: nationTaxSite.url
    });
  }
};

/**
 * 构造参数 向saas.js通信 获取报税数据
 * @param request
 * @param again 重新请求标示
 */
const postMsg4SaasData = (request, again = false) => {

  let baseInfo = window.baseInfo;
  let params = baseInfo.popupParams;
  // 判断财务报表会计制度是否一致
  let isContinue = compareCwbbZd(params, baseInfo.companyInfo, window.taxGovInfo, request.data);
  if (!isContinue) {
    caishui.notifications('填报失败：系统做账制度与税局财务报表制度不一致，请修改一致后再次申报', 6000);
    return false;
  }
  if (again) {
    params = Object.assign({}, params, baseInfo.taxInfo);
  } else {
    // taxInfo是国税页面传递的参数  将其与popup传递参数合并后传入saas去请求数据
    params = Object.assign({}, params, { taxInfo: request.data.taxInfo });
    baseInfo.taxInfo = params.taxInfo;
  }
  params.isAgain = again;
  sendMessageToContent(params, 'saas', 'getSaasData');
};

// 监听来自content-script的消息
// todo 用长连接就不要用send measage
caishui.onMessage('setBaseInfo', ({ request, sender }) => {
  initBaseInfo(request.data, sender);
});
caishui.onMessage('getNewVersionInfo', ({ request, sender }) => {
  getCurrentVersion().then(res => {
    let data = JSON.parse(res);
    let port = null;
    port = caishui.tabsConnect(sender.tab.id, { name: 'toInject' });
    port.postMessage({
      event: request.event,
      data: data
    });
  });
});
caishui.onMessage('jumpUpdate', () => {
  updateTab();
});
caishui.onMessage('declareTaxCompletion', () => {
  bgMethods.taxCompletion();
});
caishui.onMessage('fillTax', ({ request }) => {
  bgMethods.fillTax(request.data);
});
caishui.onMessage('setInvoiceInfo', ({ request, sender }) => {
  initInvoiceInfo(request.data, sender);
});
caishui.onMessage('getSaasDataDone', ({ request }) => {
  let saasData = request.data;
  if (saasData.success) {
    caishui.notifications('正在处理，请稍等！');
    let openParams = request.data.data.openParams;
    if (openParams) {
      Object.assign(
        window.baseInfo.taxInfo,
        request.data.data.openParams.taxInfo
      );
    }
    sendMessageToContent(
      { saasData: request.data, baseInfo },
      'tax',
      'setSaasData'
    );
  } else {
    caishui.notifications(saasData.data);
  }
});
caishui.onMessage('setPeriodAndType', ({ request }) => {
  let webData = baseInfo.webData || {};
  let data = request.data;
  webData = Object.assign(webData, data);
  baseInfo.webData = webData;
});
caishui.onMessage('getBaseInfo', ({ sendResponse }) => {
  sendResponse({
    event: 'getBaseInfo',
    data: baseInfo
  });
});
caishui.onMessage('getInvoiceInfo', ({ sendResponse }) => {
  if (!Object.keys(invoiceInfo).length) {
    // caishui.notifications('请从会计平台化进入！');
  }
  sendResponse({
    event: 'getInvoiceInfo',
    data: invoiceInfo
  });
});
caishui.onMessage('taxCompletionDone', ({ request }) => {
  let message = '报税完成';
  if (!request.data.success) {
    message = request.data.data || '报税失败';
  } else {
    sendMessageToContent('', '', 'refreshPage');
  }
  caishui.notifications(message);
});
caishui.onMessage('fillInputDone', ({ request }) => {
  caishui.notifications(request.data.message);
});
caishui.onMessage('backNationData', ({ request }) => {
  postMsg4SaasData(request);
});
// 调用openWeb接口失败 如token非法
caishui.onMessage('getSaasDataAgain', ({ request }) => {
  postMsg4SaasData(request, true);
});
caishui.onMessage('setReferer', ({ request }) => {
  baseInfo.referer = request.data;
});

// 获得财务报表信息
caishui.onMessage('getCwbbInfoBack', ({ request }) => {
  if (request.data) {
    window.zeroInfo.currentZeroInfo = request.data;
    window.zeroInfo.data[window.zeroInfo.currentIndex] = request.data;
    if (window.zeroInfo.currentZeroInfo.provName.includes('山城')) {
      window.zeroInfo.currentZeroInfo.provName = '重庆';
    }
    sendMessageToContent(window.zeroInfo, 'tax', 'getZeroInfoBack');
  } else {
    let message = '财务报表零申报失败';
    window.zeroInfo.currentZeroInfo.cwbbInfo = true;
    sendMessageToContent(window.zeroInfo, 'tax', 'getZeroInfoBack');
    // if (window.zeroInfo.currentZeroInfo.provName.includes('重庆')) {
    //   window.zeroInfo.currentZeroInfo.cwbbInfo = true;
    //   sendMessageToContent(window.zeroInfo, 'tax', 'getZeroInfoBack');
    // } else {
    //   message = '获取财务报表失败，进行下一家申报';
    //   sendMessageToContent(request, 'tax', 'zeroReportEnd');
    // }
    caishui.notifications(message);
  }
});
caishui.onMessage('asyncTableDetailStart', ({ request }) => {
  sendMessageToContent('', 'tax', 'asyncTableDetailStart');
});


// 报表返回
caishui.onMessage('baoBiaoDetailBack', ({ request, sender }) => {
  let timer = request.data.lastTime || 200;
  setTimeout(() => {
    if (request.data.isclose) { // 关闭页面
      chrome.tabs.remove([sender.tab.id]);
    }
    sendMessageToContent(request.data, 'zeroTax', 'baoBiaoDetailBack');
  }, timer);
});


// 新建标签页
let qsbNumber = 0;
caishui.onMessage('createNewTab', ({ request }) => {
  chrome.tabs.create({
    url: request.data.url,
    active: true
  }, (tab) => {
    if (request.data.isAutoClose) {
      let closeTime = request.data.closeTime || 3000;
      autoClosePage([tab.id], closeTime, () => {
        if (request.data.isQsb) {
          qsbNumber++;
          sendMessageToContent({ qsbNumber }, 'zeroTax', 'baoBiaoDetailBack');
          if (qsbNumber >= 3) qsbNumber = 0;
        }
      });
    }
  });
});
// 更新页面
caishui.onMessage('upDatePage', ({ request, sender }) => {
  console.log(sender, request);
  setTimeout(() => {
    chrome.tabs.update(sender.tab.id, {
      url: request.data
    }, (res) => {
      console.log(res);
    });
  }, 200);
});
// 关闭标签
caishui.onMessage('closeTabs', ({ request, sender }) => {
  chrome.tabs.remove([sender.tab.id], res => {
    console.log(res);
  });
});


// yzm
caishui.onMessage('getYzmapi', async ({ request }) => {
  let postData = request.data;
  // console.log(postData.base64Image);
  let data = await getIdentify(postData);
  let backInfo = {};
  if (data && data.data && data.data.success) {
    backInfo = data.data;
  } else {
    backInfo = { success: false };
  }
  sendMessageToContent(data.data, 'tax', 'getYzmapiBack');
});

onMessageAndSendToSaas('syncReportInfoInSaas');
onMessageAndNotifications('syncReportInfoInSaasBack');
onMessageAndSendToSaas('syncReportInSaas');
onMessageAndNotifications('syncReportInSaasBack');

// 提示
caishui.onMessage('notifications', ({ request }) => {
  let interval = request.data.interval || 2000;
  caishui.notifications(request.data.message, interval);
});

// 保存会计制度
caishui.onMessage('fixTaxGovInfo', ({ request }) => {
  window.taxGovInfo = {
    ...window.taxGovInfo,
    ...request.data
  };
})
